﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Web.UI.WebControls;

namespace Utility
{
    public static class DropDownListHelper
    {          
        /// <summary>
        /// 无限级绑定DropDownList
        /// </summary>
        /// <param name="DropDownList1">DropDownList</param>
        /// <param name="table">分类数据</param>
        /// <param name="ID">数据的主ID</param>
        /// <param name="Name">数据的Name</param>
        /// <param name="ParentID">数据的父ID</param>
        public static DropDownList BindCateGoryList(DropDownList DropDownList1, DataTable table, string ID, string Name, string ParentID)
        {
            DataTable dt = new DataTable();
            try
            {
                dt = table;
                DropDownList1.Items.Add(new ListItem("请选择分类...", "0"));
                return CreateLevelDropDown(DropDownList1, dt,ID,Name,ParentID);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }
        //绑定DropDownList
        private static DropDownList CreateLevelDropDown(DropDownList ddlst, DataTable dt,string ID,string Name,string ParentID)
        {
            ArrayList allItems = new ArrayList();
            DataRow[] rows = dt.Select("[" + ParentID + "]=" + 0);
            foreach (DataRow row in rows)
            {
                CreateLevelDropDownAssistant(dt, ref allItems, row, string.Empty, ID, Name, ParentID);
            }
            ListItem[] items = new ListItem[allItems.Count];
            allItems.CopyTo(items);
            ddlst.Items.AddRange(items);
            return ddlst;
        }
        //添加DropDownList的add
        private static void CreateLevelDropDownAssistant(DataTable dt, ref ArrayList items, DataRow parentRow, string curHeader, string ID, string Name, string ParentID)
        {
            ListItem newItem = new ListItem(curHeader + parentRow[Name].ToString(), parentRow[ID].ToString());
            items.Add(newItem);
            parentRow.Delete();

            DataRow[] rows = dt.Select("[" + ParentID + "]='" + newItem.Value + "'");
            for (int i = 0; i < rows.Length - 1; i++)
                CreateLevelDropDownAssistant(dt, ref items, rows[i], curHeader.Replace("┣", "┃").Replace("┗", "┣") + "┣", ID, Name, ParentID);//递归调用

            if (rows.Length > 0)
                CreateLevelDropDownAssistant(dt, ref items, rows[rows.Length - 1], curHeader.Replace("┣", "┃").Replace("┗", "┣") + "┗", ID, Name, ParentID);//递归调用
        }
    }
}
